//
//  UserAccount.swift
//  swft_weibo
//
//  Created by mac on 15/9/11.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class UserAccount: NSObject{
   static var savePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount")
    
    var expire_date :NSDate?
    
    /// 用户的基本认证信息
    var access_token : String?
    
    var expires_in : NSNumber?{
        
        didSet{
            
            expire_date=NSDate(timeIntervalSinceNow: expires_in!.doubleValue )
            
        }
    
    }
    
    var uid : NSNumber?
    
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    /// 用户昵称
    var screen_name: String?
    
    override init() {
        super.init()
        
    }
    /**
    自定义一个构造方法来接收字典数据
    
    :param: dic <#dic description#>
    
    :returns: <#return value description#>
    */
    init(dic:[String : AnyObject]){
        
        super.init()

        setValuesForKeysWithDictionary(dic)
    
    }
    /// 重写description的get方法，就是我们要返回的值
    override  var description : String{
    
        let proArray = ["access_token","expires_in","uid","avatar_large","screen_name"]
        
        let proDic=self.dictionaryWithValuesForKeys(proArray)
        
        return "\(proDic)"
    }

    /**
    这个方法主要是在用系统自带的kvc的时候，44行所示，如果dic的key在对像中没有属性值对应，做的操作。如果不写，出现在不在的情况就会报错。
    
    :param: value <#value description#>
    :param: key   <#key description#>
    */
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
        print(key)
    }
    
    /**
    加载屏幕显示的信息
    
    :param: completed <#completed description#>
    */
    func loadUserInformation(completed:(userAccount:UserAccount)->Void){
        
        let path = "2/users/show.json"
        let params = ["access_token":access_token!, "uid":uid!]
        NetworkTools.shareNetworkTools().GET(path , parameters: params, success: { (dataTask, jsonObject) -> Void in
            
            let dic = jsonObject as! [String:AnyObject]
            self.avatar_large = dic["avatar_large"] as? String
            self.screen_name = dic["screen_name"] as? String
            
            completed(userAccount: self)

            }) { (dataTask, error) -> Void in
                
        }
        
        
    }
    
    
    
    /**
    进行加密归档操作
    
    :param: aDecoder <#aDecoder description#>
    
    :returns: <#return value description#>
    */
    required init?(coder aDecoder: NSCoder) {
        
        access_token=aDecoder.decodeObjectForKey("access_token") as? String
        
        uid=aDecoder.decodeObjectForKey("uid") as? NSNumber
        
        expires_in=aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        
        avatar_large=aDecoder.decodeObjectForKey("avatar_large") as? String
        
        screen_name=aDecoder.decodeObjectForKey("screen_name") as? String
        
        expire_date=aDecoder.decodeObjectForKey("expire_date") as? NSDate
        
        
    }
    /**
    保存帐号信息
    */
    class func saveUserAccount(userAccount:UserAccount){
    
    
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: savePath as String)
        
    }
    /**
    取出账号的相关信息
    
    :returns: <#return value description#>
    */
    static var userAccount : UserAccount?
    class func aquireUserAccount()->UserAccount?{
        //如果userAccount有值就不用在计算了。
        if userAccount != nil{
        
            return userAccount
        }
        
         userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(savePath) as? UserAccount
        //判断如果过期了，就返回nill值
        if userAccount?.expire_date?.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            
            return nil
        }
        return userAccount
    }
    
    /**
    判断应用程序是不是已经登入了
    
    :returns:
    */
   class func userLogin()->Bool{
        
        if  UserAccount.aquireUserAccount() == nil{
        
            return false
        }else{
        
            return true
        }
    
    }

}
//MARK: - NSCoding的代理方法
extension UserAccount: NSCoding{
    /**
    进行解档操作
    
    :param: aCoder <#aCoder description#>
    */
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(expire_date, forKey:"expire_date")
        
    }
    

    
}
